package com.xy.common.utils;

import com.xy.common.Constant;
import com.xy.common.exceptions.ZookeeperException;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.logging.Logger;

public class ZookeeperUtil {

    private static final Logger logger = Logger.getLogger(ZookeeperUtil.class.getName());


    public static ZooKeeper createZookeeper() {
        // 连接参数
        String connectString = Constant.ZK_CONNECT_ADDRESS;
        // 超时时间
        int timeOut = Constant.ZK_TIME_OUT;

        return createZookeeper(connectString, timeOut);
    }

    private static ZooKeeper createZookeeper(String connectString, int timeOut) {

        CountDownLatch countDownLatch = new CountDownLatch(1);

        try {
            final ZooKeeper zooKeeper = new ZooKeeper(connectString, timeOut, event -> {
                // 只有连接成功才放心
                if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
//                    System.out.println("客户端连接成功");
                    logger.info("客户端连接成功力");
                    countDownLatch.countDown();
                }
            });
            countDownLatch.await();

            return zooKeeper;
        } catch (IOException | InterruptedException e) {
            logger.info("创建Zookeeper异常:" + e);
            throw new ZookeeperException();
        }
    }

}
